﻿using File.Api.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace File.Api.Utils
{
    public class LocalFileUtils
    {
        public static async Task UploadFileAsync(FileModel file, LocalFileParam param)
        {
            if (file.FileData == null || file.FileData.Length == 0)
            {
                return;
            }

            string dic = DateTime.Now.ToString("yyyy-MM-dd");
            var path = Path.Combine(param.RootPath, "files");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            path = Path.Combine(path, dic);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var newFileName = FileUtils.GetFileName(file.FileName);
            var filePath = Path.Combine(path, newFileName);
            using (FileStream fs = new FileStream(filePath, FileMode.Create))
            {
                await fs.WriteAsync(file.FileData, 0, file.FileData.Length);
                await fs.FlushAsync();
            }

            file.FilePath = filePath;
        }

        public static async Task DownloadFileAsync(DbFileModel file)
        {
            if (!System.IO.File.Exists(file.FilePath))
            {
                return;
            }

            byte[] data = null;
            using (FileStream fs = new FileStream(file.FilePath, FileMode.Open))
            {
                data = new byte[fs.Length];
                await fs.ReadAsync(data, 0, (int)fs.Length);
            }

            file.FileData = data;
        }
    }
}
